import { createSelector } from 'reselect'
import { reqCate, reqCateGoods } from "../../http/api";
let oldcateid=null
// 1.初始值
const initState = {
    // 1.1 初始值
    card: [],
    //2.2 初始化商品数据
    goods: [],
    // 3.1 初始化n
    n: 0
}

// types
const types = {
    // 1.2 cate的type
    CATE_CHANGE_CARD: "CATE_CHANGE_CARD",
    // 2.2goods的type
    CATE_CHANGE_GOODS: "CATE_CHANGE_GOODS",
    CATE_CHANGE_N: "CATE_CHANGE_N"
}

// reducer
export const cateReducer = (state = initState, action) => {
    switch (action.type) {
        // 1.3 修改banner 
        case types.CATE_CHANGE_CARD:
            return {
                ...state,
                card: action.card
            }
            break;
        //2.3 修改goods
        case types.CATE_CHANGE_GOODS:
            return {
                ...state,
                goods: action.goods
            }
            break;
        // 3.3 修改n
        case types.CATE_CHANGE_N:
            return {
                ...state,
                n: action.n
            }
            break;
        default:
            return state
    }
}

// actions
export const actions = {
    // 1.4 修改card  action 
    changeCard: card => ({ type: types.CATE_CHANGE_CARD, card }),
    // 2.4 修改goods
    changeGoods: goods => ({ type: types.CATE_CHANGE_GOODS, goods }),
    //    3.4 修改n
    changeN: n => ({ type: types.CATE_CHANGE_N, n }),
    // 1.6 card的数据
    reqCardAction: () => (dispatch, getState) => {
         // 1.9 将状态层作为缓存层
         let { card } = getState().cate
         if (card.length > 0) {
             return;
         }
        //   1.7发请求
        reqCate().then(res => {
            // 1.8 修改card
            if (res.data.code === 200) {
                dispatch(actions.changeCard(res.data.list))
            }
        })
    },
    // 2.6 发请求
    // 需要传参，当组件调用的时候传参
    reqGoodsAction: (index,id) => (dispatch, getState) => {
        // 如果上一次的cateid和这次一致，就不发请求
        if(oldcateid===id){
            return;
        }
        //当前这次的cateid是下一次的旧的cateid，
        oldcateid=id;
       
        dispatch(actions.changeN(index))
        
        // 2.7 发请求
        reqCateGoods({fid:id}).then(res => {
            // 2.8 修改
            if (res.data.code === 200) {
                dispatch(actions.changeGoods(res.data.list?res.data.list:[]))
                // 
            }
        })
    }
}

//1.5 导出数据
export const getCard = state => state.cate.card
// 2.5 d导出goods
export const getGoods = state => state.cate.goods
// 3.5 导出n
export const getN = state => state.cate.n

